﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Spawner : MonoBehaviour {

	private Pull Red;
	private Pull White;
	public int PoolSize=20;
	public GameObject RedPrefab;
	public GameObject WhitePrefab;


	const float BoardCf=0.1f;


	public class Pull{
		public List<GameObject> checkers = new List<GameObject>();
		public GameObject pullobj;
		public Pull(int Size, GameObject obj){
			for(int i=0; i<Size; i++){
				checkers.Add((GameObject)Instantiate(obj, new Vector3(0,-100,0), Quaternion.identity));
				checkers[i].SetActive(false);
			}
			pullobj=obj;
		}

		public void Put(Vector3 pos){
			if (checkers.Count ==0) checkers.Add((GameObject)Instantiate(pullobj, new Vector3(0,-100,0), Quaternion.identity));

			checkers [0].transform.position = pos;
			checkers [0].SetActive(true);
			checkers.RemoveAt (0);
		}

		public void Hide(GameObject go){
						checkers.Add (go);
						go.transform.position = new Vector3 (0, -100, 0);
						go.SetActive(false);
		}

	}



	void Start () {
		Red = new Pull (PoolSize, RedPrefab);
		White = new Pull (PoolSize, WhitePrefab);

		SpawnLine (0,4);
	}
	

	void Update () {
		if (Input.GetMouseButtonDown(0)){ 
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			RaycastHit hit;
			if (Physics.Raycast(ray, out hit)){
				if(hit.collider.name=="White(Clone)" || hit.collider.name=="Black(Clone)")Red.Hide(hit.collider.gameObject);
			}
		}

		if (Input.GetMouseButtonDown(1)){ 
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			RaycastHit hit;
			if (Physics.Raycast(ray, out hit)){
				Red.Put(hit.point);
			}
		}
	}


//Spawn checker
	public void Spawn(int col ,int x, int y){
		if (col == 0)Red.Put (new Vector3(BoardCf+BoardCf*2*(x-1),0.037473f,BoardCf+BoardCf*2*(y-1)));else
			White.Put (new Vector3(BoardCf+BoardCf*2*(x-1),0.037473f,BoardCf+BoardCf*2*(y-1)));
	}

	public void SpawnLine(int col, int line){
		if (col == 0){
			for(int i=-3; i<5; i++){
				Spawn(col, line, i);
			}
		}else{
			for(int i=-3; i<5; i++){
				Spawn(col, line, i);
			}
		}
	}


	
}
